package net.jsoft.pms.web.mysql.openservice;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import net.jsoft.platform.core.util.platform.PlatformUtils;
import net.jsoft.platform.core.web.BaseController;
import net.jsoft.pms.entity.openservice.OpenService;
import net.jsoft.pms.entity.openservice.PublishService;
import net.jsoft.pms.entity.ywfwqd.YwfwqdEntity;
import net.jsoft.pms.repository.openservice.OpenServiceRepository;
import net.jsoft.pms.repository.ywfwqd.YwfwqdRepository;
import net.sf.json.JSONArray;

@Controller
@RequestMapping("/openService")
public class OpenServiceController extends BaseController
{
    private String PREFIX = "/pms/mysql/openservice/";

    @Autowired
    private OpenServiceRepository repository;

    @Autowired
    YwfwqdRepository ywRepository;
    //    @Autowired
    //    PSRepository psRepository;

    /**
     * 跳转到计划管理首页
     */
    @RequestMapping("/list")
    public String list()
    {
        return PREFIX + "list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public JSONObject list(int pageSize, int pageNumber) throws ParseException
    {
        PageRequest request = new PageRequest(pageNumber - 1, pageSize, null);
        Page<OpenService> list = repository.findAll(request);

        List<Map<String, String>> resp = new ArrayList<Map<String, String>>();

        Map<String, String> t = null;
        for (OpenService p : list.getContent())
        {
            t = new HashMap<String, String>();
            t.put("id", p.getId() + "");
            t.put("version", p.getVersion());
            t.put("publishDate", p.getPublishDate() != null ? PlatformUtils.getdate(p.getPublishDate()) : "");
            t.put("note", p.getNote());
            resp.add(t);

        }

        JSONObject json = new JSONObject();
        json.put("rows", resp); //这里的 rows 和total 的key 是固定的 
        json.put("total", list.getTotalElements());
        return json;
    }

    @RequestMapping("/add")
    public String add(Model model)
    {
        List<PublishService> allOs = new ArrayList<PublishService>();
        List<PublishService> addOs = new ArrayList<PublishService>();
        List<YwfwqdEntity> all = repository.findPublishedYwfwqd();
        List<YwfwqdEntity> addition = repository.findAddtionYwfwqd();
        PublishService service = null;
        for (YwfwqdEntity y : all)
        {
            service = new PublishService();
            service.setService(y);
            service.setType("1");//all
            allOs.add(service);
        }
        for (YwfwqdEntity y : addition)
        {
            service = new PublishService();
            service.setService(y);
            service.setType("0");//add
            service.setInfluence("依赖关系：服务消费方需要同步升级；不同步升级无法校验通过。");
            service.setEditNote("修改依据：     修改说明：");
            addOs.add(service);
        }
        model.addAttribute("all", allOs);
        model.addAttribute("add", addOs);
        return PREFIX + "add";
    }

    @RequestMapping("/addSave")
    @ResponseBody
    public String addSave(String addFormData, String publishDateStr, OpenService os) throws ParseException
    {
        os.setPublishDate(PlatformUtils.getdate(publishDateStr));
        os.setAddition(addFormData);

        List<YwfwqdEntity> all = repository.findPublishedYwfwqd();
        List<PublishService> allService = new ArrayList<PublishService>();
        PublishService service = null;
        for (YwfwqdEntity y : all)
        {
            service = new PublishService();
            service.setService(y);
            service.setType("1");//all
            allService.add(service);
        }
        os.setEntire(JSONArray.fromObject(allService).toString());
        repository.save(os);
        return "ok";
    }

    @RequestMapping("/edit")
    public String edit(long id, Model model)
    {
        OpenService os = repository.findOne(id);
        model.addAttribute("all", os.getEntire());
        model.addAttribute("add", os.getAddition());
        model.addAttribute("os", os);
        return PREFIX + "edit";
    }

//    @RequestMapping("/editSaveFeild")
//    @ResponseBody
//    public String editSaveFeild(String editNote, String influence, long id) throws ParseException
//    {
//
//        //        PublishService ps = psRepository.findOne(id);
//        //        ps.setEditNote(editNote);
//        //        ps.setInfluence(influence);
//        //        psRepository.save(ps);
//        return "ok";
//    }

    @RequestMapping("/editSave")
    @ResponseBody
    public String editSave(String addFormData,String publishDateStr, OpenService os) throws ParseException
    {
        OpenService temp = repository.findOne(os.getId());
        temp.setNote(os.getNote());
        temp.setPublishDate(PlatformUtils.getdate(publishDateStr));
        temp.setVersion(os.getVersion());
        temp.setAddition(addFormData);
        repository.save(temp);
        return "ok";
    }

    @RequestMapping("/view")
    public String view(long id, Model model)
    {
        OpenService os = repository.findOne(id);
        model.addAttribute("all", os.getEntire());
        model.addAttribute("add", os.getAddition());
        model.addAttribute("os", os);
        return PREFIX + "view";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(long id) throws ParseException
    {
        repository.delete(id);
        return "ok";
    }

    @RequestMapping("/desktop")
    @ResponseBody
    public Map<String, Object> desktop(String date) throws ParseException
    {
        Map<String, Object> resp = new HashMap<String, Object>();
        Iterable<YwfwqdEntity> list = ywRepository.findAll();
        Map<String, List<YwfwqdEntity>> map = groupByDwfbzt(list);
        resp.putAll(map);
        StringBuffer sbf = new StringBuffer("服务清单<br/>");

        List<YwfwqdEntity> all = map.get("list");

        sbf.append(" 局端提供接口共计").append(all == null ? "0" : all.size()).append("个,");
        sbf.append(" 已发布").append(map.get("zt1") == null ? "0" : map.get("zt1").size()).append("个,");
        sbf.append(" 新增待发布").append(map.get("zt3") == null ? "0" : map.get("zt3").size()).append("个,");
        sbf.append(" 已修改待发布").append(map.get("zt4") == null ? "0" : map.get("zt4").size()).append("个,");
        sbf.append(" 已作废待发布").append(map.get("zt0") == null ? "0" : map.get("zt0").size()).append("个,");
        sbf.append(" 暂不发布").append(map.get("zt2") == null ? "0" : map.get("zt2").size()).append("个,");
        sbf.append(" 已作废").append(map.get("zt5") == null ? "0" : map.get("zt5").size()).append("个,");
        sbf.append(" 过时").append(map.get("zt6") == null ? "0" : map.get("zt6").size()).append("个<br/>");

        Map<String, Date> days = PlatformUtils.getDays(PlatformUtils.getdate(date));
        Map<String, String> daystr = new HashMap<String, String>();
        for (String k : days.keySet())
        {
            daystr.put(k, PlatformUtils.getdate(days.get(k)).replaceAll("-", ""));
        }
        List<YwfwqdEntity> lastWeek = ywRepository.getPeriodYwfwqd(days.get("lastWeekMonday"), days.get("lastWeekSunday"));
        map = groupByDwfbzt(lastWeek);
        sbf.append("上周(").append(daystr.get("lastWeekMonday")).append("-").append(daystr.get("lastWeekSunday")).append(")<br/>");
        sbf.append(" 局端提供接口共计").append(lastWeek == null ? "0" : lastWeek.size()).append("个,");
        sbf.append(" 已发布").append(map.get("zt1") == null ? "0" : map.get("zt1").size()).append("个,");
        sbf.append(" 新增待发布").append(map.get("zt3") == null ? "0" : map.get("zt3").size()).append("个,");
        sbf.append(" 已修改待发布").append(map.get("zt4") == null ? "0" : map.get("zt4").size()).append("个,");
        sbf.append(" 已作废待发布").append(map.get("zt0") == null ? "0" : map.get("zt0").size()).append("个,");
        sbf.append(" 暂不发布").append(map.get("zt2") == null ? "0" : map.get("zt2").size()).append("个,");
        sbf.append(" 已作废").append(map.get("zt5") == null ? "0" : map.get("zt5").size()).append("个,");
        sbf.append(" 过时").append(map.get("zt6") == null ? "0" : map.get("zt6").size()).append("个<br/>");

        List<YwfwqdEntity> thisWeek = ywRepository.getPeriodYwfwqd(days.get("thisWeekMonday"), days.get("thisWeekSunday"));
        map = groupByDwfbzt(thisWeek);
        sbf.append("本周(").append(daystr.get("thisWeekMonday")).append("-").append(daystr.get("thisWeekSunday")).append(")<br/>");
        sbf.append(" 局端提供接口共计").append(thisWeek == null ? "0" : thisWeek.size()).append("个,");
        sbf.append(" 已发布").append(map.get("zt1") == null ? "0" : map.get("zt1").size()).append("个,");
        sbf.append(" 新增待发布").append(map.get("zt3") == null ? "0" : map.get("zt3").size()).append("个,");
        sbf.append(" 已修改待发布").append(map.get("zt4") == null ? "0" : map.get("zt4").size()).append("个,");
        sbf.append(" 已作废待发布").append(map.get("zt0") == null ? "0" : map.get("zt0").size()).append("个,");
        sbf.append(" 暂不发布").append(map.get("zt2") == null ? "0" : map.get("zt2").size()).append("个,");
        sbf.append(" 已作废").append(map.get("zt5") == null ? "0" : map.get("zt5").size()).append("个,");
        sbf.append(" 过时").append(map.get("zt6") == null ? "0" : map.get("zt6").size()).append("个<br/>");

        resp.put("info", sbf.toString());

        return resp;
    }

    private Map<String, List<YwfwqdEntity>> groupByDwfbzt(Iterable<YwfwqdEntity> list)
    {
        Map<String, List<YwfwqdEntity>> map = new HashMap<String, List<YwfwqdEntity>>();

        List<YwfwqdEntity> all = new ArrayList<YwfwqdEntity>();
        String k = null;
        for (Iterator<YwfwqdEntity> iter = list.iterator(); iter.hasNext();)
        {
            YwfwqdEntity s = (YwfwqdEntity) iter.next();
            k = "zt" + s.getDwfbzt();
            if (map.containsKey(k))
            {
                List<YwfwqdEntity> newList = map.get(k);
                newList.add(s);
                map.put(k, newList);
            }
            else
            {
                List<YwfwqdEntity> newList = new ArrayList<YwfwqdEntity>();
                newList.add(s);
                map.put(k, newList);
            }

            all.add(s);
        }
        map.put("list", all);

        return map;
    }
    //
    //    private Map<String, List<Service>> groupByDwfbzt(List<Service> list)
    //    {

    //    }
    //
    //    @RequestMapping("/initServicesList")
    //    public String initServicesListPage()
    //    {
    //        return PREFIX + "serviceListPublic";
    //    }
    //
    //    @RequestMapping("/initServicesListData")
    //    @ResponseBody
    //    public Map<String, Object> initServicesListData()
    //    {
    //        Map<String, Object> resp = new HashMap<String, Object>();
    //        List<Service> publicList = mapper.findPublicServices();
    //        List<Service> addPublicList = mapper.addPublicServices();
    //        resp.put("publicList", publicList);
    //        resp.put("addPublicList", addPublicList);
    //        return resp;
    //
    //    }
    //
    //    @RequestMapping("/exportExcel")
    //    @ResponseBody
    //    public void exportExcel(HttpServletRequest request, HttpServletResponse response)
    //    {
    //        HttpSession session = request.getSession();
    //        session.setAttribute("state", null);
    //        // 生成提示信息，
    //        response.setContentType("application/vnd.ms-excel");
    //        String codedFileName = null;
    //        OutputStream fOut = null;
    //
    //        String add = this.getRequest().getParameter("add");
    //        String all = this.getRequest().getParameter("all");
    //        String form = this.getRequest().getParameter("form");
    //        String viewExport = null;
    //        List<Service> addService = JSONObject.parseArray(add, Service.class);
    //        List<Service> allService = JSONObject.parseArray(all, Service.class);
    //        List<Map> publishedServiceMap = JSONObject.parseArray(form, Map.class);
    //        PublishService publishedService = new PublishService();
    //        for (Map<String, String> m : publishedServiceMap)
    //        {
    //            if ("type".equals(m.get("name")))
    //            {
    //                viewExport = m.get("value");
    //            }
    //            else
    //            {
    //                BeanRefUtil.setFieldValue(publishedService, m.get("name"), m.get("value"));
    //            }
    //
    //        }
    //        if (!"viewExport".equals(viewExport))
    //        {
    //            String id = PlatformUtils.createPK();
    //            publishedService.setId(id);
    //            mapper.insertMain(publishedService);
    //            mapper.insertService(allService, publishedService, "all");
    //            mapper.insertService(addService, publishedService, "add");
    //        }
    //
    //        try
    //        {
    //            // 进行转码，使其支持中文文件名
    //            codedFileName = URLEncoder.encode("电子税务局局端服务清册_" + publishedService.getVersion(), "UTF-8");
    //            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
    //            workbook = new HSSFWorkbook();
    //            // 产生工作表对象
    //            HSSFSheet sheet0 = workbook.createSheet("增量发布说明");
    //
    //            HSSFCellStyle cellStyle = workbook.createCellStyle();
    //            cellStyle.setWrapText(false);
    //
    //            HSSFRow row = sheet0.createRow(0);// 创建一行
    //            row.setRowStyle(cellStyle);
    //            row.createCell(0, CellType.STRING);
    //
    //            row.createCell(0, CellType.STRING).setCellValue("序号");
    //            row.createCell(1, CellType.STRING).setCellValue("集成服务ID");
    //            row.createCell(2, CellType.STRING).setCellValue("集成服务名称");
    //            row.createCell(3, CellType.STRING).setCellValue("业务主题");
    //            row.createCell(4, CellType.STRING).setCellValue("服务类型");
    //            row.createCell(5, CellType.STRING).setCellValue("服务说明");
    //            row.createCell(6, CellType.STRING).setCellValue("XSD报文文件序号");
    //            row.createCell(7, CellType.STRING).setCellValue("增量类型");
    //            row.createCell(8, CellType.STRING).setCellValue("修改说明");
    //            row.createCell(9, CellType.STRING).setCellValue("影响分析");
    //
    //            int i = 1;
    //            for (Service p : addService)
    //            {
    //                row = sheet0.createRow(i);// 创建一行
    //                row.setRowStyle(cellStyle);
    //                row.createCell(0, CellType.STRING).setCellValue(i);
    //                row.createCell(1, CellType.STRING).setCellValue(p.getYwfwid());
    //                row.createCell(2, CellType.STRING).setCellValue(p.getYwfwmc());
    //                row.createCell(3, CellType.STRING).setCellValue(p.getYwy());
    //                row.createCell(4, CellType.STRING).setCellValue(p.getFwlx());
    //                row.createCell(5, CellType.STRING).setCellValue(p.getFwljms());
    //                row.createCell(6, CellType.STRING).setCellValue(p.getYwfwxh());
    //                //3新增待发布，4已修改待发布，5已作废待发布
    //                String zt = p.getDwfbzt();
    //                if ("3".endsWith(zt))
    //                {
    //                    zt = "新增";
    //                }
    //                else if ("4".endsWith(zt))
    //                {
    //                    zt = "修改";
    //                }
    //                else if ("5".endsWith(zt))
    //                {
    //                    zt = "作废";
    //                }
    //                row.createCell(7, CellType.STRING).setCellValue(zt);
    //                row.createCell(8, CellType.STRING).setCellValue(p.getEditNote());
    //                row.createCell(9, CellType.STRING).setCellValue(p.getInfluence());
    //                i++;
    //            }
    //
    //            // 产生工作表对象
    //            HSSFSheet sheet1 = workbook.createSheet("电子税务局局端服务清单汇总");
    //
    //            HSSFRow row1 = sheet1.createRow(0);// 创建一行
    //            row1.setRowStyle(cellStyle);
    //            row1.createCell(0, CellType.STRING);
    //
    //            row1.createCell(0, CellType.STRING).setCellValue("序号");
    //            row1.createCell(1, CellType.STRING).setCellValue("集成服务ID");
    //            row1.createCell(2, CellType.STRING).setCellValue("集成服务名称");
    //            row1.createCell(3, CellType.STRING).setCellValue("业务主题");
    //            row1.createCell(4, CellType.STRING).setCellValue("服务类型");
    //            row1.createCell(5, CellType.STRING).setCellValue("服务说明");
    //            row1.createCell(6, CellType.STRING).setCellValue("XSD报文文件序号");
    //
    //            i = 1;
    //            for (Service p : allService)
    //            {
    //                row1 = sheet1.createRow(i);// 创建一行
    //                row1.setRowStyle(cellStyle);
    //                row1.createCell(0, CellType.STRING).setCellValue(i);
    //                row1.createCell(1, CellType.STRING).setCellValue(p.getYwfwid());
    //                row1.createCell(2, CellType.STRING).setCellValue(p.getYwfwmc());
    //                row1.createCell(3, CellType.STRING).setCellValue(p.getYwy());
    //                row1.createCell(4, CellType.STRING).setCellValue(p.getFwlx());
    //                row1.createCell(5, CellType.STRING).setCellValue(p.getFwljms());
    //                row1.createCell(6, CellType.STRING).setCellValue(p.getYwfwxh());
    //                i++;
    //            }
    //
    //            fOut = response.getOutputStream();
    //            workbook.write(fOut);
    //        }
    //        catch (UnsupportedEncodingException e1)
    //        {
    //        }
    //        catch (Exception e)
    //        {
    //        }
    //        finally
    //        {
    //            try
    //            {
    //                if (fOut != null)
    //                {
    //                    fOut.flush();
    //                    fOut.close();
    //                }
    //            }
    //            catch (IOException e)
    //            {
    //            }
    //            session.setAttribute("state", "open");
    //        }
    //
    //    }
    //
    //    @RequestMapping("/scsMainList")
    //    public String scsMainList()
    //    {
    //        return PREFIX + "scsMainList";
    //    }
    //
    //    @RequestMapping("/serviceListPublicView")
    //    public String serviceListPublicView()
    //    {
    //        return PREFIX + "serviceListPublicView";
    //    }
    //
    //    @RequestMapping("/scsMainListDate")
    //    @ResponseBody
    //    public JSONObject scsMainListDate(int pageSize, int pageNumber)
    //    {
    //        PageHelper.startPage(pageNumber, pageSize);
    //        Page<PublishService> page = mapper.findPublishService();
    //        List<PublishService> list = page.getResult();
    //        JSONObject json = new JSONObject();
    //        json.put("rows", list); //这里的 rows 和total 的key 是固定的 
    //        json.put("total", page.getTotal());
    //        return json;
    //    }
    //
    //    @RequestMapping("/delete")
    //    @ResponseBody
    //    public String delete(String id)
    //    {
    //        int i = mapper.deleteMain(id);
    //        mapper.deleteSub(id);
    //        return i > 0 ? "删除成功" : "删除失败";
    //    }
    //
    //    @RequestMapping("/serviceListPublicViewDate")
    //    @ResponseBody
    //    public Map<String, Object> serviceListPublicViewDate(String id)
    //    {
    //        Map<String, Object> resp = new HashMap<String, Object>();
    //        List<Service> publicList = mapper.findPublicServicesById(id);
    //        List<Service> addPublicList = mapper.addPublicServicesById(id);
    //        PublishService publishService = mapper.findPublishServiceById(id);
    //        resp.put("publicList", publicList);
    //        resp.put("addPublicList", addPublicList);
    //        resp.put("publishService", publishService);
    //        return resp;
    //
    //    }
}
